package com.mitou.common.utils.web;

import com.mitou.base.entity.BaseDict;
import com.mitou.base.service.IBaseDictService;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典
 *
 * @author rice
 * @since 2022-01-04
 */
@Component
public class BaseDictUtil {

    @Resource
    private IBaseDictService baseDictService;

    private static BaseDictUtil baseDictUtil;

    @PostConstruct
    public void init() {
        baseDictUtil = this;
        baseDictUtil.baseDictService = this.baseDictService;
        initDictMap();
    }

    public static Map<Long, String> dictMap;

    /**
     * 如果拿map的时候为null，则重新初始化一下
     *
     * @return
     */
    public static Map<Long, String> getDictMap() {
        if (null == dictMap) {
            initDictMap();
        }
        return dictMap;
    }

    public static void setDictMap(Map<Long, String> dictMap) {
        BaseDictUtil.dictMap = dictMap;
    }

    /**
     * 初始化字典map
     */
    public static void initDictMap() {
        List<BaseDict> list = baseDictUtil.baseDictService.list();
        if (!CollectionUtils.isEmpty(list)) {
            setDictMap(list.stream().collect(Collectors.toMap(BaseDict::getDictId, BaseDict::getDictName)));
        } else {
            setDictMap(new HashMap<>(16));
        }
    }

    /**
     * 获取字典值--根据字典id
     *
     * @param id
     * @return
     */
    public static String getNameById(Long id) {
        if (null == id) {
            return "";
        }
        return getDictMap().get(id);
    }

}
